package com.sleepcamel.resteasyConfigurator.components.tree;

import java.util.List;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.widgets.Composite;

import com.sleepcamel.resteasyConfigurator.components.tree.listeners.CutCopyPasteKeyListener;
import com.sleepcamel.resteasyConfigurator.components.tree.listeners.TreeDeleteKeyListener;
import com.sleepcamel.resteasyConfigurator.components.tree.strategies.ETreeStrategy;

public class ProjectTreeViewer extends TreeViewer{

	private ETreeStrategy treeStrategy = ETreeStrategy.PACKAGE;
	private ProjectTreeLabelProvider projectTreeLabelProvider;
	private ProjectTreeContentProvider projectTreeContentProvider;
	
	public ProjectTreeViewer(Composite parent) {
		super(parent);
		setUseHashlookup(true);
		getTree().addKeyListener(new CutCopyPasteKeyListener());
		getTree().addKeyListener(new TreeDeleteKeyListener(){
			@Override
			public Object getCurrentSelection() {
				IStructuredSelection selection = (IStructuredSelection) getSelection();
				if ( selection.isEmpty() )
					return null;
				return selection.getFirstElement();
			}
		});

		MenuManager mgr = new MenuManager();
		mgr.setRemoveAllWhenShown(true);

		mgr.addMenuListener(new IMenuListener() {

			/* (non-Javadoc)
			 * @see org.eclipse.jface.action.IMenuListener#menuAboutToShow(org.eclipse.jface.action.IMenuManager)
			 */
			public void menuAboutToShow(IMenuManager manager) {
				IStructuredSelection selection = (IStructuredSelection) getSelection();
				if (!selection.isEmpty()) {
					List<Action> actions = TreeActionProvider.getInstance().getActionsForType(selection.getFirstElement(), treeStrategy);
					for(Action action:actions){
						manager.add(action);
					}
				}
			}
		});
		getControl().setMenu(mgr.createContextMenu(getControl()));
		
		projectTreeContentProvider = new ProjectTreeContentProvider();
		projectTreeLabelProvider = new ProjectTreeLabelProvider();
		setContentProvider(projectTreeContentProvider);
		setLabelProvider(projectTreeLabelProvider);
	}

	public void setStrategy(ETreeStrategy treeStrategy) {
		if ( !treeStrategy.equals(this.treeStrategy) ){
			this.treeStrategy = treeStrategy;
			updateStrategy();
		}
	}

	private void updateStrategy() {
		try{
		projectTreeContentProvider.setContentStrategy(treeStrategy.getContentStrategy().newInstance());
		projectTreeLabelProvider.setLabelStrategy(treeStrategy.getLabelStrategy().newInstance());
		}catch(Exception e){
			throw new RuntimeException(e);
		}
	}

}

